package com.diandong.airfieldmanage.main.home.manageMemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.diandong.airfieldmanage.R;
import com.diandong.airfieldmanage.main.home.manageMemo.bean.ChildEntity;
import com.diandong.airfieldmanage.main.home.manageMemo.bean.ParentEntity;
import com.diandong.airfieldmanage.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;

/**
 * Created : Yx
 * Time : 2019/9/5 17:43
 * Describe :
 */
public class ParentAdapter extends BaseExpandableListAdapter {
    private Context mContext;// 上下文
    private ArrayList<ParentEntity> mParents;// 数据源
    private OnChildTreeViewClickListener mTreeViewClickListener;// 点击子ExpandableListView子项的监听
    private List<ImageView> imageViews = new ArrayList<>();//顶级下标的所有选中按钮集合

    public ParentAdapter(Context context) {
        this.mContext = context;
    }

    public void setData(ArrayList<ParentEntity> parents) {
        this.mParents = parents;
        notifyDataSetChanged();
    }

    public ArrayList<ParentEntity> getData() {
        return mParents;
    }

    //  获得某个父项
    @Override
    public Object getGroup(int groupPosition) {
        return mParents.get(groupPosition);
    }

    //  获得父项的数量
    @Override
    public int getGroupCount() {
        return mParents != null ? mParents.size() : 0;
    }

    //  获得某个父项的id
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }


    //  获得某个父项的某个子项
    @Override
    public ChildEntity getChild(int groupPosition, int childPosition) {
        return mParents.get(groupPosition).getChilds().get(childPosition);
    }

    //  获得某个父项的某个子项的id
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    //  获得某个父项的子项数目
    @Override
    public int getChildrenCount(int groupPosition) {
        return mParents.get(groupPosition).getChilds() != null ? mParents.get(groupPosition).getChilds().size() : 0;
    }


    //  获得父项显示的view ---  一级
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_add_meeting_seluser, null);
            holder = new GroupHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (GroupHolder) convertView.getTag();
        }
        holder.update(mParents.get(groupPosition));
        imageViews.add(holder.parentGroupIV);
        boolean isSelect = mParents.get(groupPosition).getOnSelect();
        if (isSelect) {
            holder.parentGroupIV.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.hook_s));
        } else {
            holder.parentGroupIV.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.hook_n));
        }
        holder.parentGroupIV.setOnClickListener(v -> {
            if (isSelect) {
                mParents.get(groupPosition).setOnSelect(false);
                for (int i = 0; i < mParents.get(groupPosition).getChilds().size(); i++) {
                    mParents.get(groupPosition).getChilds().get(i).setOnSelect(false);
                    for (int j = 0; j < mParents.get(groupPosition).getChilds().get(i).getChildNames().size(); j++) {
                        mParents.get(groupPosition).getChilds().get(i).getChildNames().get(j).setOnSelect(false);
                    }
                }
            } else {
                mParents.get(groupPosition).setOnSelect(true);
                for (int i = 0; i < mParents.get(groupPosition).getChilds().size(); i++) {
                    mParents.get(groupPosition).getChilds().get(i).setOnSelect(true);
                    for (int j = 0; j < mParents.get(groupPosition).getChilds().get(i).getChildNames().size(); j++) {
                        mParents.get(groupPosition).getChilds().get(i).getChildNames().get(j).setOnSelect(true);
                    }
                }
            }

            notifyDataSetChanged();
        });
        return convertView;
    }


    //  获得子项显示的view   -- 二级
    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        LogUtil.iYx("---顶级下标--" + groupPosition);
        LogUtil.iYx("---下标" + groupPosition + "列表下第：" + childPosition + "项");

        //一个子项（一个一级分类下面的其中一个二级的子项）
        final ExpandableListView eListView = getExpandableListView();
        ArrayList<ChildEntity> childs = new ArrayList<ChildEntity>();//一个二级子项实体（包含标题和三级列表）
        final ChildEntity child = getChild(groupPosition, childPosition);//由于要计算高度，只能先获取到一项然后在展开收起那计算高度
        childs.add(child);
        final ChildAdapter childAdapter = new ChildAdapter(this.mContext, groupPosition, childPosition, childs);//二级标题  +  三级列表adapter   (groupPosition 一级某项数据下标)
        eListView.setAdapter(childAdapter);
        //  end  ↑

        /**
         * 子View选择后，改变数据源
         */
        childAdapter.setChildOnClicks(new ChildAdapter.ChildOnClicks() {

            /**
             * 修改顶级选中状态
             * 二级全选后反选功能
             * @param position 一级 某项数据下标
             * @param isRefresh 是否刷新顶级列表（三级列表操作后检查是否全选时不刷新）
             */
            @Override
            public void onParentSelect(int position, boolean isRefresh) {
                boolean allSelect = true;
                for (int i = 0; i < mParents.get(position).getChilds().size(); i++) {
                    if (!mParents.get(position).getChilds().get(i).getOnSelect()) {
                        allSelect = false;//有一项未选中，退出
                        break;
                    }
                }

                if (allSelect) {
                    mParents.get(position).setOnSelect(true);
                    imageViews.get(position).setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.hook_s));
                } else {
                    mParents.get(position).setOnSelect(false);
                    imageViews.get(position).setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.hook_n));
                }
                if (isRefresh) {
                    notifyDataSetChanged();
                }


            }

            /**
             * 修改二级选中状态
             * @param position  一级 某项数据下标
             * @param mChildsPosition 一级该项数据 下 对应的 二级某项数据下标
             * @param select     该项选中状态
             */
            @Override
            public void onChildGroupClicks(int position, int mChildsPosition, boolean select) {// select 二级列表某项选中状态
                mParents.get(position).getChilds().get(mChildsPosition).setOnSelect(select);
            }

            /**
             *修改三级选中状态
             * @param position 一级 某项数据下标
             * @param mChildsPosition 一级该项数据 下 对应的 二级某项数据下标
             * @param childPosition 二级该项数据 下 对应的 三级某项数据下标
             * @param select 该项选中状态
             */
            @Override
            public void onChildChildClicks(int position, int mChildsPosition, int childPosition, boolean select) {//select 三级列表某项的选中状态
                mParents.get(position).getChilds().get(mChildsPosition).getChildNames().get(childPosition).setOnSelect(select);
            }
        });

        /**
         *         子ExpandableListView展开时，因为group只有一项，所以子ExpandableListView的总高度=
         *         （子ExpandableListView的child数量 + 1 ）* 每一项的高度
         */
        eListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (child.getChildNames().size() + 1) * (int) mContext.getResources().getDimension(R.dimen.parent_expandable_list_height));
                eListView.setLayoutParams(lp);
            }
        });

        /**
         *         子ExpandableListView关闭时，此时只剩下group这一项，
         *         所以子ExpandableListView的总高度即为一项的高度
         */
        eListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) mContext.getResources().getDimension(R.dimen.parent_expandable_list_height));
                eListView.setLayoutParams(lp);
            }
        });

        /**
         *点击子ExpandableListView子项时，调用回调接口
         */
        eListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView arg0, View arg1, int groupIndex, int childIndex, long arg4) {

                if (mTreeViewClickListener != null) {
                    mTreeViewClickListener.onClickPosition(groupPosition, childPosition, childIndex);
                }
                return false;
            }
        });

        return eListView;

    }

    /**
     * 动态创建子ExpandableListView
     */
    public ExpandableListView getExpandableListView() {
        ExpandableListView mExpandableListView = new ExpandableListView(mContext);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) mContext.getResources().getDimension(R.dimen.parent_expandable_list_height));
        mExpandableListView.setLayoutParams(lp);
        mExpandableListView.setDividerHeight(0);// 取消group项的分割线
        mExpandableListView.setChildDivider(null);// 取消child项的分割线
        mExpandableListView.setGroupIndicator(null);// 取消展开折叠的指示图标
        return mExpandableListView;
    }


    /**
     * Holder优化
     */
    class GroupHolder {

        private TextView parentGroupTV;
        private ImageView parentGroupIV;

        public GroupHolder(View v) {
            parentGroupTV = (TextView) v.findViewById(R.id.amsu_title);
            parentGroupIV = (ImageView) v.findViewById(R.id.amsu_select);
        }

        public void update(ParentEntity model) {
            parentGroupTV.setText(model.getGroupName());
        }
    }

    //  按函数的名字来理解应该是是否具有稳定的id，这个方法目前一直都是返回false，没有去改动过
    @Override
    public boolean hasStableIds() {
        return false;
    }

    //  子项是否可选中，如果需要设置子项的点击事件，需要返回true
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    /**
     * 设置点击子ExpandableListView子项的监听
     */
    public void setOnChildTreeViewClickListener(OnChildTreeViewClickListener treeViewClickListener) {
        this.mTreeViewClickListener = treeViewClickListener;
    }

    /**
     * 点击子ExpandableListView子项的回调接口
     */
    public interface OnChildTreeViewClickListener {

        void onClickPosition(int parentPosition, int groupPosition, int childPosition);
    }


}
